package com.zlt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    private static final int exp = 1000 * 60 * 60;//过期时间

    private static final String secrect = "asdjklfblka$%&*(VGHJSDTRY*()";// 秘钥

    /**
     * 生成token
     * @param uid
     * @param username
     * @return
     */
    public static String toToken(String uid,String username){
        Map<String,Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");


        Date issuedAt = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(issuedAt);
        instance.add(Calendar.MILLISECOND, exp);

        return JWT.create().
                withHeader(header).//设置头部
                withIssuedAt(issuedAt).//设置发布时间
                withExpiresAt(instance.getTime()).//设置过期时间
                withSubject("*").//面向的用户
                withClaim("uid", uid).
                withClaim("username", username).
                sign(Algorithm.HMAC256(secrect));//加密
    }

    /**
     * 验证token是否有效
     * @param token
     * @return
     */
    public static boolean checkToken(String token){
        if(!StringUtil.isNotNull(token)){
            return false;
        }
        try {
            JWTVerifier build = JWT.require(Algorithm.HMAC256(secrect)).build();
            DecodedJWT verify = build.verify(token);//执行验证
        } catch (JWTVerificationException e){
            return false;
        }
        return true;
    }


    /**
     * 获取token中的信息
     * @param token
     * @param key
     * @return
     */
    public static String getMemberOfToken(String token,String key){
        if(!checkToken(token)){
            return null;
        }

        try {
            JWTVerifier build = JWT.require(Algorithm.HMAC256(secrect)).build();
            DecodedJWT verify = build.verify(token);//执行验证
            return verify.getClaim(key).asString();
        } catch (JWTVerificationException e){
            return null;
        }
    }


}
